package com.leon.openapi.common.utils;

import groovy.lang.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * leon Groovy工具类
 */
public class GroovyUtils {

    private static final Logger log = LoggerFactory.getLogger(GroovyUtils.class);
    /**
     * 动态执行 脚本字符串
     * @param scriptContent
     * @return
     */
    public Object runScript(String scriptContent){
        //执行动态脚本字符串
        Binding groovyBinding = new Binding();
        GroovyShell groovyShell = new GroovyShell(groovyBinding);

        Object returnVal = null;
        try {
            Script script = groovyShell.parse(scriptContent);
            returnVal = script.run();
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("groovy动态执行脚本出错" + e.getMessage(), e);
        }finally {
            //清除缓存
            groovyShell.getClassLoader().clearCache();
        }

        return returnVal;
    }


    /**
     *执行动态脚本文件
     * @param file
     * @return
     */
    public Object runClass(String file,String methodName, Object parms){

        Object returnVal = null;
        GroovyClassLoader loader = new GroovyClassLoader();
        try
        {
            Class groovyClass = loader.parseClass(new File(file));
            GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
            returnVal =  groovyObject.invokeMethod(methodName, parms);
        }
        catch (Exception e)
        {
            log.error("groovy动态执行脚本出错" + e.getMessage(), e);
        }finally {
            loader.clearCache();  //清除缓存，否则无法GC，导致内存溢出问题
        }
        return returnVal;
    }

}
